package com.xl.utils.util;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Objects;

/**
 * @Author xionglin
 * @Classname CodeImageUtil
 * @Description 生成验证码图片工具类
 * @Date 2019/9/3 10:46
 */
@Slf4j
@Component
public class CodeImageUtil {

    @Autowired
    private Producer captchaProducer;

    @Autowired
    private RedisUtil redisUtil;

    /**
     *  验证码字符串写进redis；将验证码图片写到前端
     * @param response
     * @param username 用户名
     */
    public void getKaptchaImage(HttpServletResponse response, String username)  {
        this.writeImage(response,null,username,true);
    }

    /**
     *  验证码字符串写进session；将验证码图片写到前端
     * @param response
     * @param session
     */
    public void getKaptchaImage(HttpServletResponse response, HttpSession session)  {
        this.writeImage(response,session,null,false);
    }

    /**
     * 校验验证码字符串
     * @param capText 带校验的验证码字符串
     * @param session
     * @return
     */
    public boolean verifyCapText(String capText,HttpSession session){
        return Objects.equals(capText,session.getAttribute(Constants.KAPTCHA_SESSION_KEY));
    }

    /**
     * 校验验证码字符串
     * @param capText  带校验的验证码字符串
     * @param username 用户名
     * @return
     */
    public boolean verifyCapText(String capText,String username){
        return Objects.equals(capText,redisUtil.get(com.xl.utils.util.Constants.SESSION_KEY + username));
    }

    /**
     * 获取一个验证码图片
     * @return
     */
    public BufferedImage getImageByCapText(){
        return captchaProducer.createImage(this.getCapText());
    }

    /**
     * 获取验证码字符串
     * @return
     */
    private String getCapText(){
        return captchaProducer.createText();
    }

    /**
     * 通过验证码字符串获取验证码图片
     * @return
     */
    private BufferedImage getImageByCapText(String capText){
        return captchaProducer.createImage(capText);
    }

    private void  writeImage(HttpServletResponse response, HttpSession session, String username,boolean useRedis){
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        // return a jpeg
        response.setContentType("image/jpeg");
        String capText = this.getCapText();
        if(useRedis){
            redisUtil.set(com.xl.utils.util.Constants.SESSION_KEY + username,capText);
        }else {
            session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        }
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            ImageIO.write(this.getImageByCapText(capText), "jpg", out);
            out.flush();
        } catch (IOException e) {
            log.error("图片写出时异常",e);
        } finally {
            if(out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    log.error("关闭ServletOutputStream流异常",e);
                }
            }
        }
    }

}